package com.fzb.forum4j.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.fzb.forum4j.po.Admin;
import com.fzb.forum4j.po.User;
import com.fzb.forum4j.service.api.IAdminService;
import com.fzb.forum4j.service.api.IWebSiteService;
import com.fzb.forum4j.util.ParseTools;
import com.opensymphony.xwork2.ActionContext;

@Controller("adminAction")
public class AdminAction extends CommonsAction<Admin>{

	
	/**
	 * 管理员后台操作
	 */
	private static final long serialVersionUID = 1L;
	
			
	@Resource(name="webSiteServiceImpl")
	private IWebSiteService webSiteService;
	
	@Resource
	private IAdminService adminService;
	
	
	/**
	 * @return
	 */
	public String login(){
		Admin admin=adminService.login(getQmd().getT());
		if(admin!=null)
		{
			setAttrToSession("adminMsg",admin);
			if(admin.getAdminRight()==1){
				User user=new User();
				user.setUserName("forum");
				user.setUserId(1);
				setAttrToSession("userMsg", user);	
			}
			ServletActionContext.getResponse().addCookie(new Cookie("mid", ParseTools.encodeBase64(getT().getUserName()+","+getT().getPassword())));
			return SUCCESS;
		}
		addActionError("请检查用户名或者密码");
		return "login";
	}
	
	/**
	 * 验证登陆前的操作， 如果cookie 中有值。从cookie 登陆
	 */
	public void validateLogin() {
		Cookie[] cs=getRequest().getCookies();
		if(cs!=null){
			for(Cookie cookie:cs){
				if(cookie.getName().equals("mid")){
					String str[]=ParseTools.decodeBase64(cookie.getValue()).split(",");
					if(str.length==2){
						getT().setUserName(str[0]);
						getT().setPassword2(str[1]);
					}
					break;
				}
			}
		}
		clearActionErrors();
	}
	
	/**注销(同时清空cookie)
	 * @return
	 */
	public String logout(){
		ActionContext.getContext().getSession().clear();
		Cookie[] cs=getRequest().getCookies();
		if(cs!=null){
			for(Cookie cookie:cs){
				if(cookie.getName().equals("mid")){
					cookie.setMaxAge(0);
					ServletActionContext.getResponse().addCookie(cookie);
				}
			}
		}
		return "login";
	}
	public String configWebsite(){
		return "website";
	}
	/**更新webSite 中的配配置信息
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String updateWebSite(){
		Map<String, Object> webSite=ActionContext.getContext().getParameters();
		if(webSite.isEmpty()){
			Map<String,String> tweb=new HashMap<String, String>();
			for(Entry<String,Object> wweb:webSite.entrySet()){
				tweb.put(wweb.getKey(), ((String[])wweb.getValue())[0]);
				
			}
			((Map<String,String>)ActionContext.getContext().getApplication().get("webSite")).putAll(webSiteService.updateWebSite(tweb));
			return SUCCESS;
		}
		return "error";
	}
}
